package com.yang.usb.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;

import com.yang.usbserial.util.LogUtils;

public class OpenAccessoryReceiver extends BroadcastReceiver {
    private OpenAccessoryListener mOpenAccessoryListener;

    public OpenAccessoryReceiver(OpenAccessoryListener mOpenAccessoryListener) {
        this.mOpenAccessoryListener = mOpenAccessoryListener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        UsbAccessory usbAccessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
        if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
            LogUtils.e("USB设备已连接");
        } else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
            LogUtils.e("USB设备已断开 ");
            mOpenAccessoryListener.usbDetached();
        } else if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
            if (usbAccessory != null) {
                mOpenAccessoryListener.openAccessoryModel(usbAccessory);
            } else {
                mOpenAccessoryListener.openAccessoryError();
            }
        } else {
            mOpenAccessoryListener.openAccessoryError();
        }
    }


    public interface OpenAccessoryListener {
        /**
         * 打开Accessory模式
         *
         * @param usbAccessory
         */
        void openAccessoryModel(UsbAccessory usbAccessory);

        /**
         * 打开设备(手机)失败
         */
        void openAccessoryError();

        /**
         * usb断开连接
         */
        void usbDetached();
    }
}
